package com.gitee.cui.redis.jedis;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;

/**
 * Redis中Hash类型数据测试
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/7 19:50
 **/
@Slf4j
public class HashTest {

    private static final String KEY = "config";

    @Test
    public void hashTest() {
        Jedis jedis = new Jedis("localhost", 6379);
        jedis.del(KEY);

        // 设置值
        jedis.hset(KEY, "ip", "127.0.0.1");
        // 取值
        log.info("jedis.hget(KEY, \"ip\"): " + jedis.hget(KEY, "ip"));
        // 取得类型：hash
        log.info("jedis.type(KEY): " + jedis.type(KEY));
        // 批量添加元素
        Map<String, String> configMap = new HashMap<>();
        configMap.put("port", "8080");
        configMap.put("maxalive", "3000");
        configMap.put("weight", "1.0");
        // 执行批量添加
        jedis.hmset(KEY, configMap);

        // 获取数据，获取全部键值对
        log.info("jedis.hgetAll(KEY): " + jedis.hgetAll(KEY));
        // 批量获取，通过key获取对应的值
        log.info("jedis.hmget(KEY, \"ip\", \"port\", \"maxalive\"): " + jedis.hmget(KEY, "ip", "port", "maxalive"));
        // 获取所有的key
        log.info("jedis.hkeys(KEY): " + jedis.hkeys(KEY));
        // 获取所有的value
        log.info("jedis.hvals(KEY): " + jedis.hvals(KEY));

        // 获取数量
        log.info("jedis.hlen(KEY): " + jedis.hlen(KEY));
        // 判断key是否存在
        log.info("jedis.hexists(KEY, \"ip\"): " + jedis.hexists(KEY, "ip"));
        // 删除一个field
        jedis.hdel(KEY, "weight");
        log.info("jedis.hkeys(KEY): " + jedis.hkeys(KEY));

        jedis.close();
    }
}
